package edu.sdbi.judge.controller;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.mapper.DailyVisitsMapper;
import edu.sdbi.judge.service.impl.Judge_14;
import edu.sdbi.judge.util.ErrorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/statistics")
public class StaticData14Controller {
    //    private static final Map<String, Object> mockData = new HashMap<>();
//
//    static {
//        // 初始化模拟数据
//        mockData.put("newsId", "1");
//        mockData.put("visits", 1000);
//        mockData.put("visitCount1", 500);
//        mockData.put("data1", "2025-06-14");
//        mockData.put("visitCount2", 5001);
//        mockData.put("data2", "2025-06-15");
//
//    }
    @Autowired
    private Judge_14 judge14;
    @Autowired
    private DailyVisitsMapper dailyVisitsMapper;
    private static final Map<String, Integer> VISIT_DATA = new HashMap<>();

    static {
        // 初始化测试数据
        VISIT_DATA.put("2025-06-10", 120);
        VISIT_DATA.put("2025-06-11", 135);
        VISIT_DATA.put("2025-06-12", 142);
        VISIT_DATA.put("2025-06-13", 128);
        VISIT_DATA.put("2025-06-14", 164);
        VISIT_DATA.put("2025-06-15", 172);
        VISIT_DATA.put("2025-06-16", 185);
        VISIT_DATA.put("2025-06-17", 190);
        VISIT_DATA.put("2025-06-18", 178);
        VISIT_DATA.put("2025-06-19", 205);
        VISIT_DATA.put("2025-06-20", 210);
    }

    @Value("${test.startDate:2025-06-14 00:00:00}")
    private String startDate;

    @Value("${test.endDate:2025-06-14 23:59:59}")
    private String endDate;
    @Value("${test.startDate:2025-06-15 00:00:00}")
    private String startDate2;

    @Value("${test.endDate:2025-06-15 23:59:59}")
    private String endDate2;

    /**
     * 模拟新闻访问统计接口
     *
     * @param newsID    新闻ID
     * @param startDate 开始日期（格式：yyyy-MM-dd）
     * @param endDate   结束日期（格式：yyyy-MM-dd）
     * @return 统计结果
     */
    @GetMapping("/dayVisits")
    public String getNewsComment(@RequestParam("newsID") String newsID,
                                 @RequestParam("startDate") String startDate,
                                 @RequestParam("endDate") String endDate) {


        Integer dailyVisits = dailyVisitsMapper.getDailyVisitsByRange(startDate, endDate);
        Integer dailyVisits2 = dailyVisitsMapper.getDailyVisitsByRange(startDate, endDate);
        System.out.println(dailyVisits);
        System.out.println(dailyVisits2);

        try {

            // 验证新闻ID
            if (!"1".equals(newsID)) {
                return buildErrorResult(400, "无效的新闻ID");
            }
            // 验证日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false); // 严格日期格式检查
            // 解析开始日期和结束日期
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);
            // 验证日期范围有效性
            if (start.after(end)) {
                return buildErrorResult(400, "开始日期不能晚于结束日期");
            }
            // 构建日期范围内的访问量数据
            List<Map<String, Object>> resultData = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);

            while (!calendar.getTime().after(end)) {
                String dateStr = dateFormat.format(calendar.getTime());
                int visits = VISIT_DATA.getOrDefault(dateStr, 0);

                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", dateStr);
                dayData.put("visitsCount", visits);
                resultData.add(dayData);

                // 日期加1天
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            while (!calendar.getTime().after(end)) {
                String dateStr = dateFormat.format(calendar.getTime());
                int visits = VISIT_DATA.getOrDefault(dateStr, 0);

                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", dateStr);
                dayData.put("visitsCount", visits);
                resultData.add(dayData);

                // 日期加1天
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }


            // 构建成功响应
            JsonResult result = new JsonResult();
            result.setCode(200);
            result.setMsg("新增成功");
            result.setData(resultData);

            return JSONObject.toJSONString(result);
        } catch (ParseException e) {
            return buildErrorResult(400, "日期格式错误，请使用yyyy-MM-dd格式");
        } catch (Exception e) {
            return buildErrorResult(500, ErrorUtil.stackTraceToString(e));
        }

    }

    /**
     * 构建错误响应
     *
     * @param code    错误码
     * @param message 错误信息
     * @return 错误响应JSON字符串
     */
    private String buildErrorResult(int code, String message) {
        JsonResult result = new JsonResult();
        result.setCode(code);
        result.setMsg(message);
        return JSONObject.toJSONString(result);
    }
}
